import json
import time
import paho.mqtt.client as mqtt
MQTTHOST = "121.40.144.89"
MQTTPORT = 1883

#--------MQTT---------------
echo = True


mqttClient = mqtt.Client()
# 连接MQTT服务器
def on_mqtt_connect():
  mqttClient.connect(MQTTHOST, MQTTPORT, 60)
  mqttClient.loop_start()
# publish 消息
def on_publish(topic, payload, qos):
  mqttClient.publish(topic, payload, qos)
# 消息处理函数
def on_message_come(lient, userdata, msg):
    global echo
#   print(str(msg.topic),':',str(msg.payload))
    res = str(msg.payload).split('\\n')
    for it in res:
        print("  ",it)
    echo = True
# subscribe 消息
def on_subscribe(topic):
  mqttClient.subscribe(topic, 1)
  mqttClient.on_message = on_message_come # 消息到来处理函数



def mqtt_main():
    on_mqtt_connect()
    on_subscribe("statue/")


if __name__ == '__main__':
    mqtt_main()

    ID = input("Enter dev ID: ")
    print(ID)
    while True:
        while echo==False:
            time.sleep(0.1)
        cmd = input("{} $".format(ID))
        echo = False
        cmd_info={"ID":ID,"shell": cmd}
        # print(cmd_info)
        mqttClient.publish("dbg/", json.dumps(cmd_info))
        


